package com.example.easybuy.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.easybuy.config.AlipayProperties;
import com.example.easybuy.entity.CarDetail;
import com.example.easybuy.entity.Order;
import com.example.easybuy.entity.OrderDetail;
import com.example.easybuy.entity.Product;
import com.example.easybuy.service.CarService;
import com.example.easybuy.service.OrderService;
import com.example.easybuy.service.ProductService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ZfbController {
    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CarService carService;

    @RequestMapping("/zf")
    public void zf(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) throws AlipayApiException, IOException {
        //初始化一个 AlipayClient，用于与支付宝的 API 进行交互。参数包括网关 URL、应用 ID、商户私钥等。
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayProperties.gatewayUrl, alipayProperties.getApp_id(), AlipayProperties.merchant_private_key, "json", AlipayProperties.charset, AlipayProperties.alipay_public_key, AlipayProperties.sign_type);

        //PC版页面支付请求对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        //手机版页面支付对象
//        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();


        //设置同步回调地址
        alipayRequest.setReturnUrl(AlipayProperties.return_url);
        //设置异步回调地址
        alipayRequest.setNotifyUrl(AlipayProperties.notify_url);

        String total_amount = params.get("total_amount").toString();
        String out_trade_no = params.get("out_trade_no").toString();
        String subject = params.get("subject").toString();

        Map<String, Object> map = new HashMap<>();
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        map.put("out_trade_no", out_trade_no);
        map.put("total_amount", total_amount);
        map.put("subject", subject);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(map);
        alipayRequest.setBizContent(json);
        //请求
        // alipayClient.pageExecute(alipayRequest)：使用 alipayClient 对象调用 pageExecute 方法，发送一个页面请求。
        //alipayRequest：包含了支付宝请求的必要参数（例如订单信息、回调地址等）。
        //.getBody()：获取请求的响应体，通常是一个 HTML 表单，支付宝会通过这个表单进行页面跳转。
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(result);//将支付宝返回的HTML内容写入HTTP响应体中。这样，当浏览器接收到这个响应时，就会显示支付宝的支付页面。
        response.getWriter().close();
    }

    @RequestMapping("/return_url")
    public void return_url(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println("同步回调执行");
        // 获取支付宝 GET 过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }


        // 调用 SDK 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayProperties.alipay_public_key, AlipayProperties.charset, AlipayProperties.sign_type);

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            out.println("<h1>交易成功！</h1>");
            out.println("支付宝交易号:" + trade_no + "<br/>商户订单号:" + out_trade_no + "<br/>付款金额:" + total_amount);
            out.println("<div><span>点击跳转到订单页面：</span><a href='http://192.168.102.202:8090/Member_Order.html'>订单页面</a></div>");
        } else {
            out.println("验签失败");
        }
        out.close();
    }

    @RequestMapping("/notify_url")
    public void notify_url(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("异步回调开始执行");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayProperties.alipay_public_key, AlipayProperties.charset, AlipayProperties.sign_type); //调用SDK验证签名

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<h1>支付完成  异步</h1>");
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                System.out.println("交易关闭！");
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                Map<String, Object> map = new HashMap<>();
                map.put("itStatus", 1);//已支付
                map.put("trade_no", trade_no);//支付宝交易号
                map.put("serialNumber", out_trade_no);
                orderService.updateOrder(map);
                int orderId = orderService.getOrder(map).getId();
                String loginName = orderService.getOrder(map).getLoginName();
                map.put("orderId", orderId);
                List<OrderDetail> list = orderService.selectOrderDetail(map);
                Product product;
                Map<String, Object> map1;//获取商品对象 更改库存
                for (OrderDetail orderDetail : list) {
                    carService.delCar(loginName, orderDetail.getProductId());
                    map1 = new HashMap<>();
                    map1.put("id", orderDetail.getProductId());
                    product = productService.getPro(map1);
                    map1.put("preStock", product.getPreStock() - orderDetail.getQuantity());
                    productService.updatePro(map1, null);
                }
                stringRedisTemplate.delete(orderId + "-order");
                System.out.println("付款完成！");
                out.println("<h1>交易成功！</h1>");
                out.println("支付宝交易号:" + trade_no + "<br/>商户订单号:" + out_trade_no + "<br/>付款金额:" + total_amount);
                out.println("<div><span>点击跳转到订单页面：</span><a href='http://192.168.102.202:8090/Member_Order.html'>订单页面</a></div>");
                out.println("success");
            }

        } else {//验证失败
            out.println("fail");
            System.out.println("验证失败");
        }
        out.close();
        System.out.println("异步回调执行完成");
    }


    @RequestMapping("/refund")
    @ResponseBody
    public String refund(@RequestParam Map<String, Object> params) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayProperties.gatewayUrl, alipayProperties.getApp_id(), AlipayProperties.merchant_private_key, "json", AlipayProperties.charset, AlipayProperties.alipay_public_key, AlipayProperties.sign_type);
        //退款请求对象
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        // 构建退款请求的具体参数模型。
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        String out_trade_no = params.get("outTradeNo").toString();
        // 设置商户订单号
        model.setOutTradeNo(out_trade_no);

        // 设置退款金额
        model.setRefundAmount(params.get("refundAmount").toString());

        // 设置退款原因说明
        model.setRefundReason(params.get("refundReason").toString());
        String out_request_no = System.currentTimeMillis() + "";
        model.setOutRequestNo(out_request_no);//out_request_no 在支付宝退款中用于标识每个退款请求的唯一性。它可以帮助商户防止同一笔退款请求的重复提交，因为支付宝会根据这个编号来判断请求是否已处理。这在处理并发退款时尤其重要，确保每个退款只被处理一次。通过生成一个独特的编号（如使用时间戳），商户可以有效管理退款流程并减少潜在的错误。
        request.setBizModel(model);
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            Map<String, Object> map = new HashMap<>();
            map.put("serialNumber", out_trade_no);
            map.put("itStatus", 2);//已退款
            orderService.updateOrder(map);
            int orderId = orderService.getOrder(map).getId();
            map.put("orderId", orderId);
            List<OrderDetail> list = orderService.selectOrderDetail(map);
            Product product;
            Map<String, Object> map1;//获取商品对象 更改库存
            for (OrderDetail OrderDetail : list) {
                map1 = new HashMap<>();
                map1.put("id", OrderDetail.getProductId());
                product = productService.getPro(map1);
                map1.put("stock", product.getStock() + OrderDetail.getQuantity());
                productService.updatePro(map1, null);
            }
            return "退款成功！";
        } else {
            return "退款失败！";
        }
    }
}